package com.hula.onion.book.server.spider.platforms.hengyirong;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("hengYiRongSpider")
public class HengYiRongSpider extends SpiderCommon {
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.hengyirong.com/site/login.html";


    @Autowired
    private HengYiRongSpiderHelper niWoDaiSpiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);
        //1.1 组装模拟登陆参数
        //TODO 验证码 需要将生成时的cookie传递过来
        HttpClientContext httpContext = HttpClientContext.create();
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpContext.setCookieStore(cookieStore);
        try {
            Map<String, Object> params =
                    niWoDaiSpiderHelper.installRequestParams(loginForm, "");
            //1.2 登陆直接跳转到个人信息页
            String responseStr = HttpUtils.post(LOGIN_URL, params,httpContext);

            //2.2 解析HTML
            AccountInfo accountBalance = niWoDaiSpiderHelper.parseAccountBalance(responseStr);

            if (null != accountBalance) {
                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
                commonResponse.setData(accountBalance);
            } else {
                commonResponse.setMsg(niWoDaiSpiderHelper.parsErrorMessage(responseStr));
                commonResponse.setCode("-1");
            }

        } catch (Exception e) {
            logger.error("[hengYiRongSpider] Install request params error!");
        }

        return commonResponse;
    }
}
